﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using YunSpace.Core;
using YunSpace.Domain.Entity.MiniSite;
using YunSpace.Domain.IRepository.MiniSite;
using YunSpace.Repository.MiniSite;
using System.Collections.Generic;
using System.Linq;
using YunSpace.Data;
using System.Data.Common;
using MySql.Data.MySqlClient;
using YunSpace.Domain.ViewModel.MiniSite;
using YunSpace.Domain.Entity.SiteMgr;
using System;
#endregion

namespace YunSpace.Application.MiniSite
{
    public class SiteOrderApp
    {
        private ISiteOrderRepository service = new SiteOrderRepository();


        public List<SiteOrderEntity> GetList(Pagination pagination, string queryJson)
        {
            var expression = ExtLinq.True<SiteOrderEntity>();
            var queryParam = queryJson.ToJObject();

            return service.FindList(expression, pagination);
        }

        public SiteOrderEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public string SubmitForm(SiteOrderEntity entity, string keyValue)
        {
            OrderStatusRecordEntity orderrecord = new OrderStatusRecordEntity();
            if (!string.IsNullOrEmpty(keyValue))
            {
                entity.Modify(keyValue);
                // service.Update(entity);
                using (var db = new RepositoryBase().BeginTrans())
                {
                    db.Update<SiteOrderEntity>(entity);
                    // 更新订单状态时往记录表里面插入一条记录
                    orderrecord.Create();
                    orderrecord.f_orderid = entity.F_Id;
                    orderrecord.f_operationtype = entity.F_Status.ToString();
                    orderrecord.F_CreatorUserId = entity.F_CustomerId;
                    db.Insert<OrderStatusRecordEntity>(orderrecord);

                    db.Commit();
                }
            }
            else
            {
                entity.Create();
                // 状态 0.未付订金; 1.已付订金; 2.等待确认; 3.已付款; 4.待举办; 5.已举办; 6.退款中; 7.已退款; 8.结束
                entity.F_Status = 0;
                // 是否评论
                entity.F_IsComment = false;
                //service.Insert(entity);

                using (var db = new RepositoryBase().BeginTrans())
                {
                    //插入订单表
                    db.Insert<SiteOrderEntity>(entity);
                    orderrecord.Create();
                    orderrecord.f_orderid = entity.F_Id;
                    orderrecord.f_operationtype = entity.F_Status.ToString();
                    orderrecord.F_CreatorUserId = entity.F_CustomerId;
                    db.Insert<OrderStatusRecordEntity>(orderrecord);

                    db.Commit();
                }
            }
            return entity.F_Id;
        }

        /// <summary>
        /// 1.0 完成订单（创建相关活动）
        /// </summary>
        public void CompleteSiteOrder(SiteActivityEntity siteActivityEntity)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                var siteorderEntity = db.FindEntity<SiteOrderEntity>(siteActivityEntity.F_OrderId);
                //siteorderEntity.Modify(siteActivityEntity.F_OrderId);
                // 状态 0.未付订金; 1.已付订金; 2.等待确认; 3.已付款待举办; 4.进行中; 5.已举办; 6.退款中; 7.已退款; 8.结束
                siteorderEntity.F_Status = 3;
                db.Update<SiteOrderEntity>(siteorderEntity);

                siteActivityEntity.Create();
                // 状态 0.活动初始; 1.未开始; 2.进行中; 3.已结束; 4.待评价; 5.已完结
                siteActivityEntity.F_Status = 0;
                db.Insert<SiteActivityEntity>(siteActivityEntity);

                OrderStatusRecordEntity orderStatus = new OrderStatusRecordEntity();
                orderStatus.Create();
                orderStatus.f_orderid = siteorderEntity.F_Id;
                orderStatus.f_operationtype = siteorderEntity.F_Status.ToString();
                orderStatus.F_CreatorUserId = siteorderEntity.F_CustomerId;
                db.Insert<OrderStatusRecordEntity>(orderStatus);

                db.Commit();
            }
        }

        /// <summary>
        /// 支付定金
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="operationId"></param>
        /// <param name="status"></param>
        /// <param name="remark"></param>
        /// <param name="orderPrice"></param>
        public void UpdateSiteOrderStatusDJ(string orderId, string operationId, int peopleNum, int activityType, bool isEat, int status, string remark, decimal orderPrice, DateTime? F_DecorationTime, DateTime F_ActivityTime)
        {
            var entity = service.FindEntity(orderId);
            
            OrderStatusRecordEntity orderStatus = new OrderStatusRecordEntity();
            SitePayFlowRecordEntity payFlow = new SitePayFlowRecordEntity();
            using (var db = new RepositoryBase().BeginTrans())
            {
                entity.Modify(orderId);
                entity.F_Status = status;
                entity.F_Remark = remark;
                entity.F_PeopleNum = peopleNum;
                entity.F_ActivityType = activityType;
                entity.F_IsEat = isEat;
                entity.F_ActivityTime = F_ActivityTime;
                entity.F_DecorationTime = F_DecorationTime;
                db.Update<SiteOrderEntity>(entity);

                orderStatus.Create();
                orderStatus.f_orderid = entity.F_Id;
                orderStatus.f_operationtype = entity.F_Status.ToString();
                orderStatus.F_Mark = remark;
                orderStatus.F_CreatorUserId = operationId;
                db.Insert<OrderStatusRecordEntity>(orderStatus);

                payFlow.Create();
                payFlow.F_PayCash = orderPrice;
                payFlow.F_OrderId = entity.F_Id;
                payFlow.F_IsPost = 0;
                payFlow.F_CreatorUserId = operationId;
                db.Insert<SitePayFlowRecordEntity>(payFlow);

                db.Commit();
            }
        }

        /// <summary>
        /// 支付尾款
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="operationId"></param>
        /// <param name="status"></param>
        /// <param name="orderPrice"></param>
        //public void UpdateSiteOrderStatusWK(string orderId, string operationId, bool isPreview, DateTime? previewStartTime, DateTime? previewEndTime, int status, decimal orderPrice)
        public void UpdateSiteOrderStatusWK(string orderId, string operationId, int status, decimal orderPrice)
        {
            var entity = service.FindEntity(orderId);
            
            OrderStatusRecordEntity orderStatus = new OrderStatusRecordEntity();
            SitePayFlowRecordEntity payFlow = new SitePayFlowRecordEntity();
            using (var db = new RepositoryBase().BeginTrans())
            {
                entity.Modify(orderId);
                entity.F_Status = status;
                //entity.F_IsPreview = isPreview;
                //entity.F_PreviewStartTime = previewStartTime;
                //entity.F_PreviewEndTime = previewEndTime;
                db.Update<SiteOrderEntity>(entity);

                orderStatus.Create();
                orderStatus.f_orderid = entity.F_Id;
                orderStatus.f_operationtype = entity.F_Status.ToString();
                orderStatus.F_CreatorUserId = operationId;
                db.Insert<OrderStatusRecordEntity>(orderStatus);

                payFlow.Create();
                payFlow.F_PayCash = orderPrice;
                payFlow.F_OrderId = entity.F_Id;
                payFlow.F_IsPost = 0;
                payFlow.F_CreatorUserId = operationId;
                db.Insert<SitePayFlowRecordEntity>(payFlow);

                db.Commit();
            }
        }

        /// <summary>
        /// 更新场地订单的状态
        /// </summary>
        public void UpdateSiteOrderDetail(string keyValue, string operationId, bool isEat, int peopleNum, int activityType, bool isPreview, DateTime? previewStartTime, DateTime? previewEndTime, string remark = "", decimal totalPrice = 0, List<CostRecordActionModel> costList = null, InvoiceActionModel invoice = null)
        {
            var entity = service.FindEntity(keyValue);
            OrderStatusRecordEntity orderStatus = new OrderStatusRecordEntity();

            using (var db = new RepositoryBase().BeginTrans())
            {
                entity.Modify(keyValue);
                entity.F_IsEat = isEat;
                entity.F_PeopleNum = peopleNum;
                entity.F_ActivityType = activityType;
                entity.F_IsPreview = isPreview;
                entity.F_PreviewStartTime = previewStartTime;
                entity.F_PreviewEndTime = previewEndTime;
                if (!remark.IsNullOrEmpty() && remark.Length > 0) entity.F_Remark = remark;
                if (totalPrice > 0) entity.F_TotalPrice = totalPrice;
                db.Update<SiteOrderEntity>(entity);

                orderStatus.Create();
                orderStatus.f_orderid = entity.F_Id;
                orderStatus.f_operationtype = entity.F_Status.ToString();
                orderStatus.F_Mark = remark;
                orderStatus.F_CreatorUserId = operationId;
                db.Insert<OrderStatusRecordEntity>(orderStatus);

                if (!costList.IsEmpty() && costList.Any())
                {
                    db.Delete<CostRecordEntity>(p => p.F_OrderId == entity.F_Id);

                    costList.ForEach(item =>
                    {
                        var costrecord = new CostRecordEntity();
                        costrecord.Create();
                        costrecord.F_OrderId = entity.F_Id;
                        costrecord.F_SiteId = entity.F_SiteId;
                        costrecord.F_SpaceId = entity.F_SpaceId;
                        costrecord.F_CostId = item.F_Id;
                        costrecord.F_Cost = item.F_Cost;
                        costrecord.F_CategoryName = item.F_CategoryName;
                        costrecord.F_CreatorUserId = entity.F_CustomerId;
                        db.Insert<CostRecordEntity>(costrecord);
                    });
                }

                if (invoice != null)
                {
                    InvoiceEntity item = new InvoiceEntity();
                    item.Create();
                    item.F_Type = invoice.F_Type;
                    item.F_Detail = invoice.F_Detail;
                    item.F_CustomerId = entity.F_CustomerId;
                    item.F_CompanyNo = invoice.F_CompanyNo;
                    item.F_Title = invoice.F_Title;
                    item.F_Email = invoice.F_Email;
                    item.F_CreatorUserId = entity.F_CreatorUserId;
                    item.F_OrderId = entity.F_Id;
                    item.F_IsOpen = 0;
                    db.Insert<InvoiceEntity>(item);
                }

                db.Commit();
            }
        }

        /// <summary>
        /// 更新场地订单的状态
        /// </summary>
        public void UpdateSiteOrderStatus(string keyValue, string operationId, int status, string remark = "", decimal totalPrice = 0, List<CostRecordActionModel> costList = null, InvoiceActionModel invoice = null)
        {
            var entity = service.FindEntity(keyValue);
            entity.Modify(keyValue);

            entity.F_Status = status;
            if (!remark.IsNullOrEmpty() && remark.Length > 0)
            {
                // SiteOrderEnum.WaitReturn
                if (status == 6)
                {
                    entity.F_UnsubscribeRemark = remark;
                }
                else
                {
                    entity.F_Remark = remark;
                }
            }
            if (totalPrice > 0)
            {
                entity.F_TotalPrice = totalPrice;
            }
            //service.Update(entity);
            OrderStatusRecordEntity orderStatus = new OrderStatusRecordEntity();

            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Update<SiteOrderEntity>(entity);

                orderStatus.Create();
                orderStatus.f_orderid = entity.F_Id;
                orderStatus.f_operationtype = entity.F_Status.ToString();
                orderStatus.F_Mark = remark;
                orderStatus.F_CreatorUserId = operationId;
                db.Insert<OrderStatusRecordEntity>(orderStatus);

                if (!costList.IsEmpty() && costList.Any())
                {
                    db.Delete<CostRecordEntity>(p => p.F_OrderId == entity.F_Id);

                    costList.ForEach(item =>
                    {
                        var costrecord = new CostRecordEntity();
                        costrecord.Create();
                        costrecord.F_OrderId = entity.F_Id;
                        costrecord.F_SiteId = entity.F_SiteId;
                        costrecord.F_SpaceId = entity.F_SpaceId;
                        costrecord.F_CostId = item.F_Id;
                        costrecord.F_Cost = item.F_Cost;
                        costrecord.F_CategoryName = item.F_CategoryName;
                        costrecord.F_CreatorUserId = entity.F_CustomerId;
                        db.Insert<CostRecordEntity>(costrecord);
                    });
                }

                if (invoice != null)
                {
                    InvoiceEntity item = new InvoiceEntity();
                    item.Create();
                    item.F_Type = invoice.F_Type;
                    item.F_Detail = invoice.F_Detail;
                    item.F_CustomerId = entity.F_CustomerId;
                    item.F_CompanyNo = invoice.F_CompanyNo;
                    item.F_Title = invoice.F_Title;
                    item.F_Email = invoice.F_Email;
                    item.F_CreatorUserId = entity.F_CreatorUserId;
                    item.F_OrderId = entity.F_Id;
                    item.F_IsOpen = 0;
                    db.Insert<InvoiceEntity>(item);
                }

                db.Commit();
            }
        }

        /// <summary>
        /// 更新活动订单的状态
        /// </summary>
        public void UpdateActivityOrderStatus(string keyValue, int status, string operationId)
        {
            var entity = service.FindEntity(keyValue);
            entity.Modify(keyValue);

            entity.F_Status = status;
            //service.Update(entity);

            OrderStatusRecordEntity orderStatus = new OrderStatusRecordEntity();
            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Update<SiteOrderEntity>(entity);

                orderStatus.Create();
                orderStatus.f_orderid = entity.F_Id;
                orderStatus.f_operationtype = entity.F_Status.ToString();
                orderStatus.F_CreatorUserId = operationId;
                db.Insert<OrderStatusRecordEntity>(orderStatus);

                db.Commit();
            }

        }

        /// <summary>
        /// 2.0 获取用户的所有场地订单
        /// </summary>
        /// <param name="lastId"></param>
        /// <param name="count"></param>
        public List<SiteOrderEntity> GetSiteAllOrders(string customerId, string lastId, int count)
        {
            var query = service.IQueryable(p => p.F_CustomerId == customerId);
            var result = query.ToList();

            return result;
        }

        /// <summary>
        /// 3.0 获取用户的行待支付场地订单
        /// </summary>
        /// <param name="lastId"></param>
        /// <param name="count"></param>
        public List<SiteOrderEntity> GetSiteWaitPayOrders(string customerId, string lastId, int count)
        {

            var query = service.IQueryable(p => p.F_CustomerId == customerId && p.F_Status == 2);
            var result = query.ToList();

            return result;
        }

        /// <summary>
        /// 4.0 获取用户的行待评论场地订单
        /// </summary>
        /// <param name="lastId"></param>
        /// <param name="count"></param>
        public List<SiteOrderEntity> GetSiteWaitCommentOrders(string customerId, string lastId, int count)
        {

            var query = service.IQueryable(p => p.F_CustomerId == customerId && p.F_Status == 5);
            var result = query.ToList();

            return result;
        }

        /// <summary>
        /// 5.0 获取场地订单详细
        /// </summary>
        public SiteOrderActionModel GetSiteOrderDetail(string orderDetailId, int type, string customerId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_SiteId,a.F_SpaceId,a.F_CustomerId,e.F_UserName,e.F_Phone,a.F_ActivityId,a.F_PeopleNum,a.F_ActivityType, si.F_ItemName F_ActivityTypeName,a.F_IsEat, a.F_IsPreview, a.F_PreviewStartTime, a.F_PreviewEndTime,a.F_Type,a.F_ParentId,a.F_ReserveTime,a.F_UnsubscribeRemark,
                                b.title sitename, b.address,c.title as spacename,c.through_three_areas,d.path,a.F_StartTime,a.F_EndTime,c.market_price,c.inner_price,a.F_TotalPrice,a.F_Price,a.F_OrderPrice,a.F_CreatorTime,
                                a.F_Remark,a.F_IsInvoice,a.F_IsComment,a.F_Status,datediff(a.F_EndTime,a.F_StartTime)+1 orderDays 
                                ,case when fa.F_CustomerId is null then 0 else 1 end isfavorite ,b.F_SupplierId
                                from MiniSite_SiteOrder a                                
                                inner join SL_Site b on a.F_SiteId = b.F_Id  and b.F_Category=1
                                left join (select max(cc.F_Id) F_Id,max(cc.inner_price) inner_price,max(cc.through_three_areas) through_three_areas,max(cc.market_price) market_price,max(cc.title) title from SL_Space cc group by cc.F_Id) c on c.F_Id=a.F_SpaceId
                                left join SL_Photos d on a.F_SpaceId=d.photoable_id and d.is_cover=1
                                left join MiniSite_Customer e on e.F_Id=a.F_CustomerId
                                left join Sys_ItemsDetail si on a.F_ActivityType = si.F_ItemCode and si.F_ItemId='a7eaa4b2-4c17-43ed-a30b-9fd8632bd0a4'
                                left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite where 1=1 {1}) fa on b.F_Id=fa.f_favoriteid and a.F_CustomerId=fa.F_CustomerId
                                where a.f_id=@orderDetailId {0}";
                if (type == 3)
                {
                    strSql = @"select a.F_Id,a.F_SiteId,a.F_SpaceId,a.F_CustomerId,e.F_UserName,e.F_Phone,a.F_ActivityId,F_PeopleNum,a.F_ActivityType, '' F_ActivityTypeName,a.F_IsEat, a.F_IsPreview, a.F_PreviewStartTime, a.F_PreviewEndTime,a.F_Type,a.F_ParentId,a.F_ReserveTime,a.F_UnsubscribeRemark,
                                b.F_Title sitename, '' address,b.F_Subject as spacename,'' through_three_areas,d.path,b.F_StartTime,b.F_EndTime,b.F_Price market_price,b.F_Price inner_price,a.F_TotalPrice,a.F_Price,a.F_OrderPrice,a.F_CreatorTime,
                                a.F_Remark,a.F_IsInvoice,a.F_IsComment,a.F_Status,datediff(a.F_EndTime,a.F_StartTime)+1 orderDays 
                                ,case when fa.F_CustomerId is null then 0 else 1 end isfavorite, '' F_SupplierId 
                                from MiniSite_SiteOrder a                                
                                inner join MiniSite_SiteActivity b on a.F_ActivityId = b.F_Id
                                left join SL_Photos d on a.F_ActivityId=d.photoable_id and d.is_cover=1
                                left join MiniSite_Customer e on e.F_Id=a.F_CustomerId
                                left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite where 1=1 {1}) fa on b.F_Id=fa.f_favoriteid and a.F_CustomerId=fa.F_CustomerId
                                where a.f_id=@orderDetailId {0}";
                }
                strSql = string.Format(strSql, customerId.IsNullOrEmpty() ? "" : " and a.F_CustomerId=@customerId", customerId.IsNullOrEmpty() ? "" : " and F_CustomerId=@customerId");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@orderDetailId", orderDetailId),
                    new MySqlParameter("@customerId", customerId)
                };
                return db.FindList<SiteOrderActionModel>(strSql, parameter).FirstOrDefault();
            }
        }

        public List<OrderStatusRecordActionModel> GetSiteOrderStatusById(string orderId)
        {
            var result = new List<OrderStatusRecordActionModel>();
            using (var db = new RepositoryBase())
            {
                var order = service.FindEntity(orderId);

                var strSql = @"select b.F_Id,b.f_operationType as  f_Status,b.f_orderId,b.F_Mark,b.F_CreatorUserId,
                                case when b.f_operationType=0 then '等待下单' 
                                     when b.f_operationType=1 then '已付定金' 
                                     when b.f_operationType=2 then '档期确认'
                                     when b.f_operationType=3 then '订单完成' 
                                     when b.f_operationType=6 then '申请退款' 
                                     when b.f_operationType=7 then '退款完成'
                                     else '' end f_operationType,
                                b.F_CreatorTime from MiniSite_orderStatusRecord b 
                                where b.f_orderId=@orderId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@orderId", orderId)
                };
                var data = db.FindList<OrderStatusRecordActionModel>(strSql, parameter);

                #region 处理订单状态的逻辑
                // 返回的结果集模型
                var dic = new Dictionary<int, List<OrderStatusRecordActionModel>> {
                    { 1, new List<OrderStatusRecordActionModel> {
                            new OrderStatusRecordActionModel {
                                f_operationtype = "预订成功",
                                f_Status = 1
                            },
                            new OrderStatusRecordActionModel {
                                f_operationtype = "等待确认",
                                f_Status = 2
                            },
                            new OrderStatusRecordActionModel {
                                f_operationtype = "已付尾款",
                                f_Status = 3
                            },
                            new OrderStatusRecordActionModel {
                                f_orderid = orderId,
                                f_operationtype = "入驻日期",
                                F_CreatorTime = order.F_StartTime,
                                f_Status = 9999,
                                F_CreatorUserId = order.F_CreatorUserId
                            }
                         }
                    },
                    { 2, new List<OrderStatusRecordActionModel> {
                            new OrderStatusRecordActionModel {
                                f_operationtype = "申请退款",
                                f_Status = 6
                            },
                            new OrderStatusRecordActionModel {
                                f_operationtype = "退款完成",
                                f_Status = 7
                            }
                        }
                    }
                };
                

                switch (order.F_Status)
                {
                    case 6:
                    case 7:
                        result = dic[2];
                        break;
                    default:
                        result = dic[1];
                        break;
                }
                data.ForEach(item1 => {
                    result.ForEach(item2 => {
                        if (item1.f_Status == item2.f_Status)
                        {
                            item2.F_Id = item1.F_Id;
                            item2.f_orderid = item1.f_orderid;
                            item2.F_CreatorTime = item1.F_CreatorTime;
                            item2.F_CreatorUserId = item1.F_CreatorUserId;
                        }
                    });
                });

                
                #endregion

            }
            return result;
        }


        public List<SiteOrderActionModel> GetOrderList(string customerId, int status, int type, string lastId, int count)
        {
            using (var db = new RepositoryBase())
            {
                var result = new List<SiteOrderActionModel>();
                // 空间相关的逻辑 type = 2
                var strSql = @"select a.F_Id,a.F_SiteId,a.F_SpaceId,a.F_CustomerId,e.F_UserName,e.F_Phone,a.F_ActivityId,a.F_Type,a.F_ParentId,a.F_ReserveTime,
                                b.title sitename,c.title as spacename,c.through_three_areas,d.path,c.market_price,c.inner_price,a.F_StartTime,a.F_EndTime,a.F_TotalPrice,a.F_Price,a.F_OrderPrice,a.F_CreatorTime,
                                a.F_Remark,a.F_IsInvoice,a.F_IsComment,a.F_Status,datediff(a.F_EndTime,a.F_StartTime)+1 orderDays from MiniSite_SiteOrder a                                
                                left join SL_Site b on a.F_SiteId = b.F_Id and b.F_Category=1
                                left join SL_Space c on a.F_SpaceId = c.F_Id
                                left join SL_Photos d on a.F_SiteId=d.photoable_id and d.is_cover=1
                                left join MiniSite_Customer e on e.F_Id=a.F_CustomerId
                               where 1=1 and a.F_Type=@type {0} {1} {2} {3} {4}";
                if (type == 3)
                {
                    // 活动相关的逻辑 type=3
                    strSql = @"select a.F_Id,a.F_SiteId,a.F_SpaceId,a.F_CustomerId,e.F_UserName,e.F_Phone,a.F_ActivityId,a.F_Type,a.F_ParentId,a.F_ReserveTime,
                                 b.F_Title sitename,b.F_Subject as spacename,'' through_three_areas,d.path,b.F_Price market_price,b.F_Price  inner_price,b.F_StartTime,b.F_EndTime,a.F_TotalPrice,a.F_Price,a.F_OrderPrice,a.F_CreatorTime,
                                 a.F_Remark,a.F_IsInvoice,a.F_IsComment,a.F_Status,datediff(a.F_EndTime,a.F_StartTime)+1 orderDays from MiniSite_SiteOrder a                                
                              left join MiniSite_SiteActivity b on a.F_ActivityId = b.F_Id
                              left join SL_Photos d on a.F_ActivityId=d.photoable_id and d.is_cover=1
                              left join MiniSite_Customer e on e.F_Id=a.F_CustomerId
                             where 1=1 and a.F_Type=@type {0} {1} {2} {3} {4}";
                }
                strSql = string.Format(strSql,
                            customerId.IsNullOrEmpty() ? "" : "AND a.F_customerid = @customerId",
                            status == -1 ? "" : status==0? " and a.f_status in(@status,2)" : " and a.f_status=@status",
                            status == 8 && type==2 ? " AND F_IsComment=false " : "",
                            lastId.IsNullOrEmpty() ? "" : "AND a.F_Id < @fId",
                            "  ORDER BY a.F_CreatorTime DESC,a.F_Status desc  limit 0," + count + "");

                DbParameter[] parameter =
                  {
                        new MySqlParameter("@customerId", customerId),
                        new MySqlParameter("@fId", lastId),
                        new MySqlParameter("@status",status),
                        new MySqlParameter("@type",type == 0 ? 2: type)
                };
                result = db.FindList<SiteOrderActionModel>(strSql, parameter);

                return result;
            }
        }

        /// <summary>
        /// 6.0 获取场地空间档期是否冲突
        /// </summary>        
        /// <returns>是否存在档期</returns>
        public bool IsExistSchedule(string F_SiteId, string F_SpaceId, string startTime, string endTime)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select * from MiniSite_SiteOrder a where a.F_SiteId=@F_SiteId and a.F_SpaceId=@F_SpaceId
                                and DATE_FORMAT(a.F_EndTime,'%Y-%m-%d')>= DATE_FORMAT(@startTime, '%Y-%m-%d')
                                and DATE_FORMAT(a.F_EndTime, '%Y-%m-%d')<=DATE_FORMAT(@endTime, '%Y-%m-%d')
                                and DATE_FORMAT(a.F_StartTime, '%Y-%m-%d')>=DATE_FORMAT(@startTime, '%Y-%m-%d')
                                and DATE_FORMAT(a.F_StartTime, '%Y-%m-%d')<=DATE_FORMAT(@endTime, '%Y-%m-%d')";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_SiteId", F_SiteId),
                    new MySqlParameter("@F_SpaceId", F_SpaceId),
                    new MySqlParameter("@startTime", startTime),
                    new MySqlParameter("@endTime", endTime)
                };
                List<SiteOrderEntity> list = db.FindList<SiteOrderEntity>(strSql, parameter);
                if (list.Count > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }


        public List<OrderScheduleActionModel> GetSpaceScheduleDate(string spacefid)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT space.F_SiteId  siteFid,table1.F_SpaceId spaceFid,table1.F_Date scheduledate  from MiniSite_ScheduleRecord  table1
                                        LEFT JOIN SL_Space  space ON  table1.F_SpaceId = space.F_Id  WHERE    table1.F_SpaceId=@spacefid
                                        GROUP BY  table1.F_SpaceId  ORDER BY table1.F_CreatorTime  ASC";
                DbParameter[] parameter =
               {
                    new MySqlParameter("@spacefid", spacefid)
                };
                return db.FindList<OrderScheduleActionModel>(strSql, parameter);
            }
        }


        /// <summary>
        /// 获取商户场地的订单信息
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="lastId"></param>
        /// <param name="count"></param>
        /// <param name="state"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<SiteMgrSiteOrderActionModel> GetSupplierOrderData(string supplierId, string lastId, int count, string state, string orderId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select site.title sitename,space.title as spacename,com.F_UserName,com.F_NickName,com.F_Phone ,
                            o.*,mi.F_OrderId,mi.F_Type,mi.F_Detail,mi.F_Title,mi.F_CompanyNo,mi.F_IsOpen,mi.F_Email
                            from MiniSite_SiteOrder o inner join SL_Site site on o.F_SiteId=site.F_Id inner join SL_Space space on space.F_Id=o.F_SpaceId
                            left join MiniSite_Invoice mi on mi.F_OrderId=o.F_Id inner join MiniSite_Customer com on com.F_Id=o.F_CustomerId  
                            where 1=1 {0} {2} {3} {4} limit 0,{1}";

                strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND o.F_CreatorTime<(select F_CreatorTime from MiniSite_SiteOrder where F_Id=@lastId)", count,
                    supplierId.IsNullOrEmpty() ? "" : " and site.F_SupplierId=@supplierId",
                    orderId.IsNullOrEmpty() ? "" : " and o.F_Id=@orderId ",
                    state.IsNullOrEmpty() ? "" : " and o.F_Status in(@state)");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@lastId", lastId),
                    new MySqlParameter("@supplierId", supplierId),
                    new MySqlParameter("@orderId", orderId),
                    new MySqlParameter("@state", state)
                };
                return db.FindList<SiteMgrSiteOrderActionModel>(strSql, parameter);
            }
        }


        public void CreateSitePayFlowRecord(string orderId, decimal orderPrice, string operationId)
        {
            using (var db = new RepositoryBase())
            {
                var payFlow = new SitePayFlowRecordEntity();
                payFlow.Create();
                payFlow.F_PayCash = orderPrice;
                payFlow.F_OrderId = orderId;
                payFlow.F_IsPost = 0;
                payFlow.F_CreatorUserId = operationId;
                db.Insert<SitePayFlowRecordEntity>(payFlow);
            }
        }
        /// <summary>
        /// 更新订单的评论状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool UpdateIsCommentState(string orderId)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                var siteorderEntity = db.FindEntity<SiteOrderEntity>(orderId);
                siteorderEntity.F_IsComment = true;
                db.Update<SiteOrderEntity>(siteorderEntity);
                db.Commit();
            }
            return true;
        }


        /// <summary>
        /// 获取场地空间是否有不能下架的场地
        /// </summary>        
        /// <returns>是否存在档期</returns>
        public int SiteOrderCount(string F_SiteId , string F_SpaceId)
        {
            using (var db = new RepositoryBase())
            {
                //状态 0.未付订金; 1.已付订金; 2.等待确认; 3.已付款; 4.待举办; 5.已举办; 6.退款中; 7.已退款; 8.结束;9:确认档期;10:档期已满;
                var strSql = @"select * from MiniSite_SiteOrder a where F_Status in(1,2,3,4,5,6,9) {0}{1}";
                strSql = string.Format(strSql,
                   F_SiteId.IsNullOrEmpty() ? "" : " and  a.F_SiteId=@F_SiteId",
                   F_SpaceId.IsNullOrEmpty() ? "" : " and a.F_SpaceId=@F_SpaceId ");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_SiteId", F_SiteId),
                    new MySqlParameter("@F_SpaceId", F_SpaceId)
                };
                List<SiteOrderEntity> list = db.FindList<SiteOrderEntity>(strSql, parameter);
                return list.Count;
            }
        }
    }
}

